//
//  YDUserInfoController.m
//  CRM
//
//  Created by ios on 16/8/1.
//  Copyright © 2016年 YD_iOS. All rights reserved.
//

#import "YDUserInfoController.h"

#import "YDUserInfoCell.h"
#import "YDUserInfoHeaderView.h"
#import "CustomSheetView.h"

#import "YDMyInfoModel.h"

#import "UIImageView+WebCache.h"
#import "AFNetworking.h"

@interface YDUserInfoController () <CustomSheetViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) YDUserInfoHeaderView *headerView;

@end

@implementation YDUserInfoController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self setViewData];
}

- (void)setViewData
{
    self.title = @"个人信息";
    self.navigationController.navigationBarHidden = NO;

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib(@"YDUserInfoCell")];
    self.tableView.backgroundColor = kViewControllerBackgroundColor;
    
    self.headerView = [YDUserInfoHeaderView instanceUserInfoHeaderView];
    
    WEAKSELF
    self.headerView.ButtonClick = ^{
        CustomSheetView *sheet = [[CustomSheetView alloc] initWithBottomButtonCount:1 otherButtonTitleArray:@[@"拍摄",@"从相册中选择"]];
        sheet.delegate = weakSelf;
        [kWindow addSubview:sheet];
    };
    self.tableView.tableHeaderView = self.headerView;
}

- (void)actionSheetDidSelect:(NSInteger)index
{
    if (index == 0 || index == 1) {
        
        UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
        
        //获取方式1：通过相册（呈现全部相册），UIImagePickerControllerSourceTypePhotoLibrary
        //获取方式2，通过相机，UIImagePickerControllerSourceTypeCamera
        //获取方法3，通过相册（呈现全部图片），UIImagePickerControllerSourceTypeSavedPhotosAlbum
        PickerImage.sourceType = index == 0 ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypePhotoLibrary;
        PickerImage.allowsEditing = YES;
        PickerImage.delegate = self;
        [self presentViewController:PickerImage animated:YES completion:nil];
    }
}

#pragma mark - ==================tableview delegate==================
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YDUserInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YDUserInfoCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.lineView.hidden = NO;
    
    if (indexPath.row == 0) {
        cell.titleLabel.text = @"姓名:";
        cell.subTitleLabel.text = self.myInfoModel.memberName;
    } else if (indexPath.row == 1) {
        cell.titleLabel.text = @"手机:";
        cell.subTitleLabel.text = self.myInfoModel.mobilePhone;
    } else if (indexPath.row == 2) {
        cell.titleLabel.text = @"职称:";
        cell.subTitleLabel.text = self.myInfoModel.jobTitle;
    } else {
        cell.titleLabel.text = @"品牌:";
        cell.subTitleLabel.text = self.myInfoModel.brandsName;
        cell.lineView.hidden = YES;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 55.0f;
}

#pragma mark - =====================头像===========================
//PickerImage完成后的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //定义一个newPhoto，用来存放我们选择的图片。
    UIImage *newPhoto = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    self.headerView.iconView.image = newPhoto;
    
    //压缩图片
    NSData *fileData = UIImageJPEGRepresentation(self.headerView.iconView.image, 0.1);
    
    //获取正在编辑的图片
    
    __block NSURL *imageUrl = [info valueForKey:UIImagePickerControllerReferenceURL];
    
    __block NSString *imageName;
    //获取图片的名字信息
    ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
    {
        ALAssetRepresentation *representation = [myasset defaultRepresentation];
        imageName = [representation filename];//self.imageName是属性
        
        if (imageName == nil) imageName = [NSString stringWithFormat:@"%d.PNG", arc4random() % 10000];
        //上传图片
        [self uploadImageWithData:fileData imageName:imageName];
    };
    
    ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
    [assetslibrary assetForURL:imageUrl
                   resultBlock:resultblock
                  failureBlock:nil];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)uploadImageWithData:(NSData *)fileData imageName:(NSString *)imageName
{
    //1.创建管理者对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //2.上传文件
    NSDictionary *dict = @{};
    
    NSString *urlString = [NSString stringWithFormat:@"%@sid=%@", kUserIconAddress, getNSUser(kAPP_SID)];;
    
    [manager POST:urlString parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        //这个就是参数
        [formData appendPartWithFileData:fileData name:@"file" fileName:imageName mimeType:@"image/png"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //打印下上传进度
        NSLog(@"%lf",1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //请求成功
        NSLog(@"请求成功：%@",responseObject);
        
        if ([[responseObject valueForKey:@"code"] isEqualToString:@"S_OK"]) {
            
            [MBProgressHUD showTips:@"上传成功" toView:self.view];
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //请求失败
        NSLog(@"请求失败：%@",error);
    }];
    
}


- (void)setMyInfoModel:(YDMyInfoModel *)myInfoModel
{
    _myInfoModel = myInfoModel;
    
    [self.headerView.iconView sd_setImageWithURL:[NSURL URLWithString:myInfoModel.headPic] placeholderImage:[UIImage imageNamed:@"little_head_boy"]];
}

@end
